<template>
  <el-container class="system-notice-container">
    <el-aside width="210px">
      <div class="left-menu">
        <el-scrollbar class="left-menu-scrollbar" wrap-class="menu-scrollbar-wrapper">
          <!-- 消息类别 -->
          <div
            @click.prevent="selectMenuItem(item)"
            class="left-menu-item"
            :class="{'is-active': item.value == active}"
            :key="index"
            v-for="(item, index) in listType">
            <table class="text">
              <tbody>
              <tr>
                <td width="45"><img :src="item.image" class="img-circle user-header pull-left" alt=""></td>
                <td>
                  <div class="text-box">
                    <div>{{ item.text }}</div>
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>

          <!-- Im 消息 -->
          <div
            @click.prevent="selectIm(worker)"
            class="left-menu-item"
            :class="{'is-active': '4' == active && currentWorkerId == worker.userId}"
            :key="worker.userId"
            v-for="(worker) in sortMembers">
            <table class="text">
              <tbody>
              <tr>
                <td width="45">
                  <el-badge
                    class="im-un-read-badge"
                    :hidden="GET_IM_CHART_DIALOG_UN_READ_LENGTH(worker.groupIdArr) <= 0"
                    :value="GET_IM_CHART_DIALOG_UN_READ_LENGTH(worker.groupIdArr)"
                  >
                    <img :src="getImUserPhoto(worker)" class="img-circle user-header pull-left" alt="头像">
                  </el-badge>
                </td>
                <td>
                  <div class="text-box">
                    <div>{{ worker.userName }}</div>
                    <div
                      v-if="GET_IM_CHART_DIALOG_LAST_MESSAGE(worker.groupIdArr)"
                      v-html="GET_IM_CHART_DIALOG_LAST_MESSAGE(worker.groupIdArr)"
                    ></div>
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-scrollbar>
      </div>
    </el-aside>
    <el-container>
      <el-header>
        <el-col :span="24">
          <el-row>
            <el-col :span="24">
              <OrderHeaderInfo v-if="active == '4'" :orderInfo="{}"></OrderHeaderInfo>
              <p class="text-center" v-else>{{ title }}</p>
            </el-col>
          </el-row>
          <div class="grey-line"></div>
        </el-col>
      </el-header>
      <el-main>

        <div class="text-center" v-if="active === '1'">
          小二客服
        </div>
        <Portlet v-if="active === '2'">
          <el-table
            :data="tableData"
            :show-header="false"
            stripe
            style="width: 100%;"
          >
            <el-table-column>
              <template slot-scope="scope">
                <el-row class="order-el-row">
                  <el-col :span="22">
                    {{scope.row.title}}
                  </el-col>
                  <el-col :span="2" style="text-align: right">
                    <a href="javascript:void(0);" @click.prevent="delMessage(scope.row.id)"><i class="el-icon-close"></i></a>
                  </el-col>
                </el-row>
                <el-row class="marginBottom8">
                  <el-col :span="24">
                    {{scope.row.content}}
                  </el-col>
                  <el-col :span="24" style="text-align: right">
                    {{scope.row.foundtime | unixTimestampFilter('YYYY-MM-DD HH:mm')}}
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-col :span="24">
            <Pagination style="margin-top: 20px" class="pull-right" :total-item="totalItem" @pagination="pagination"
                        @sizeChange="sizeChange" :perItem="params.pageSize"></Pagination>
          </el-col>
        </Portlet>
        <Portlet v-if="active === '3' && !isShowDetail">
            <el-table
              :data="tableData"
              :show-header="false"
              stripe
              style="width: 100%;"
            >
              <el-table-column>
                <template slot-scope="scope">
                  <el-row class="order-el-row">
                    <el-col :span="22">
                      <span style="font-size: 13px;" :class="{'font-red': !scope.row.state, 'font-green': scope.row.state}">{{scope.row.state == 2 ? "[已读]" : "[未读]"}}</span>{{scope.row.title}}
                    </el-col>
                    <el-col :span="2" style="text-align: right">
                      <!--<i class="el-icon-close"></i>-->
                    </el-col>
                  </el-row>
                  <el-row class="marginBottom8">
                    <el-col :span="3" v-if="scope.row.imgAddress.length">
                      <img :src="'/api/ms-mongodb/file/download?fileId=' + handleJsonStringArr(scope.row.imgAddress)[0]"
                           style="width: 120px; height: 90px;"/>
                    </el-col>
                    <el-col :span="scope.row.imgAddress.length > 0 ? 21 : 24">
                      <el-row>
                        <el-col :span="24">
                          {{scope.row.content.substring(0, 120) + "..."}}
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span="12">
                          <el-button @click.prevent="showDetail(scope.row)" type="text">查看详情</el-button>
                        </el-col>
                        <el-col :span="12" style="text-align: right">{{scope.row.foundtime | unixTimestampFilter('YYYY-MM-DD HH:mm')}}</el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
            <el-col :span="24">
              <Pagination style="margin-top: 20px" class="pull-right" :total-item="totalItem" @pagination="pagination"
                          @sizeChange="sizeChange" :perItem="params.pageSize"></Pagination>
            </el-col>
          </Portlet>
        <Portlet v-if="active === '3' && isShowDetail">
          <template slot="tools">
            <el-button @click.prevent="closeDetail" type="primary">返回列表</el-button>
          </template>
          <div class="portlet light portlet-fit">
            <div class="portlet-title">
              <div class="caption" style="text-align: center; width: 100%;">
                <p style="color:#1F2D3D;font-size:24px;font-weight: 600"> {{systemMessageDetail.title}}</p>
                <span style="color:#1F2D3D;font-size:12px;font-weight: 200"> {{systemMessageDetail.foundName}} {{systemMessageDetail.foundtime | unixTimestampFilter}} </span>
              </div>
            </div>
            <div class="portlet-body" style="width:100%; height: 100%; overflow: auto">
              <p v-html="systemMessageDetail.content"></p>
            </div>
          </div>
          <div class="clearfix"></div>
        </Portlet>
          <IMBox v-if="active == '4'"></IMBox>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
import {copy, merge, handleJsonStringArr, dotData} from '@/utils'
import {getInitMembers} from '@/utils/im'
import lodash from 'lodash'
import OrderHeaderInfo from '@/components/Im/OrderHeaderInfo'
import IMBox from '@/components/Im/IMBox'
import {mapGetters, mapActions} from 'vuex'
import {unixTimestampFilter} from '@/filters'
export default {
  components: {
    OrderHeaderInfo,
    IMBox
  },
  data() {
    return {
      active: this.$store.getters.GET_NOTICE_TYPE,
      type: 1,
      params: {
        pageSize: 5,
        pageNum: 1
      },
      totalItem: 0,
      tableData: [],
      listType: this.$store.getters.GET_NOTICE_TYPE_ARR || [],
      systemMessageDetail: {},
      unreadTotal: '',
      isShowDetail: false
    }
  },
  filters: {
    unixTimestampFilter
  },
  computed: {
    title() {
      if (Array.isArray(this.computedListType)) {
        const item = this.computedListType.filter(v => v.value === this.active)
        return dotData(item, '[0].text')
      }
      return '标题'
    },
    sortMembers() { // 对师傅进行排序
      return lodash.orderBy(this.imMembers, ['userName'], ['asc'])
    },
    computedListType() {
      return this.listType.concat(this.sortMembers)
    },
    currentWorkerGroupIdArr() {
      return this.currentWorker.groupIdArr || []
    },
    ...mapGetters({
      imMembers: 'GET_IM_CHART_DIALOG_GROUP_MEMBERS_BY_WORKER',
      currentWorker: 'GET_IM_CHART_CURRENT_WORKER',
      currentWorkerId: 'GET_IM_CHART_CURRENT_WORKER_ID',
      GET_IM_CHART_DIALOG_UN_READ_LENGTH: 'GET_IM_CHART_DIALOG_UN_READ_LENGTH',
      GET_IM_CHART_DIALOG_LAST_MESSAGE: 'GET_IM_CHART_DIALOG_LAST_MESSAGE'
    })
  },
  watch: {
    '$route'() {
      this.getGroupMembers()
    },
    'active'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      switch (this.active) {
        case '1':
          console.log('小二客服')
          break
        case '2':
          console.log('订单助手')
          this.type = 2
          this.url = '/ms-message-api/message/find-message-type'
          this.getTableData()
          break
        case '3':
          this.type = 1
          this.url = '/ms-message-api/message/find-message-type'
          this.getTableData()
          break
      }
    }
  },
  created() {
    switch (this.active) {
      case '1':
        console.log('小二客服')
        break
      case '2':
        console.log('订单助手')
        this.type = 2
        this.url = '/ms-message-api/message/find-message-type'
        this.getTableData()
        break
      case '3':
        this.type = 1
        this.url = '/ms-message-api/message/find-message-type'
        this.getTableData()
        break
    }
    this.getGroupMembers()
  },
  methods: {
    handleJsonStringArr,
    selectMenuItem(item) {
      // 设置活动模块
      this.active = item.value
    },
    pagination(page) {
      this.params.pageNum = page
      this.searchFunc()
    },
    sizeChange(size) {
      this.params.pageSize = size
      this.searchFunc()
    },
    searchFunc(search) {
      this.getTableData()
    },
    getTableData() {
      let data = copy(this.search, true)
      data = merge(data, this.params)
      data.type = this.type
      this.$ajax.table(this.url, data).then(response => {
        this.tableData = response.data || []
        this.totalItem = response.totalItem
        this.tableData.forEach(v => {
          v.imgAddress = handleJsonStringArr(v.imgAddress)
        })
      })
    },
    // 获取im用户列表
    getGroupMembers() {
      getInitMembers()
    },
    // 获取Im 侧边图标
    userPhoto(item) {
      if (item.userPhoto) {
        return `/api/ms-mongodb/file/download?fileId=${item.userPhoto}`
      } else {
        return '/static/images/im/kf.png'
      }
    },
    // 选择Im消息
    selectIm(worker) {
      this.active = '4'
      if (worker.type === 'workerGroup') {
        if (this.currentWorkerId === worker.userId) {
          return
        }
        this.SET_IM_CHART_DIALOG_GROUP_ID(worker.groupIdArr[0])
      } else if (worker.type === 'single') {
        this.SET_IM_CHART_DIALOG_GROUP_ID(worker.groupId)
      }
    },
    // 获取im用户的头像
    getImUserPhoto(worker) {
      if (worker.type === 'single') {
        return worker.avatar
      }
      if (worker.userPhoto) {
        return `/api/ms-mongodb/file/download?fileId=${worker.userPhoto}`
      } else {
        return '/static/images/im/kf.png'
      }
    },
    // 显示详细
    showDetail(data) {
      this.getSystemMessageDetail(data.id, data.source)
      this.isShowDetail = true
    },
    // 关闭详细
    closeDetail() {
      this.getTableData()
      this.isShowDetail = false
    },
    // 请求公告详情
    getSystemMessageDetail(id, contentId) {
      this.$ajax.get('/ms-fahuobao-user/content/findContentInfo', {contentId: contentId}).then(response => {
        if (response) {
          this.systemMessageDetail = response.data
        }
      })
      // 标识已读
      this.$ajax.get('/ms-message-api/message/read', {messageId: id}).then(response => {
        this.getSystemMessageCount()
      })
    },
    // 请求公告详情数据统计
    getSystemMessageCount() {
      this.$ajax.get('/ms-message-api/message/count-type-subType', {type: '1', subType: 'content'}).then(response => {
        if (response) {
          this.unreadTotal = response.count
        }
      })
    },
    // 删除订单消息
    delMessage(messageId) {
      this.$ajax.get('/ms-message-api/message/deleteMessage', {
        messageId: messageId
      })
      this.getTableData()
    },
    ...mapActions([
      'SET_IM_CHART_DIALOG_GROUP_ID'
    ])
  }
}
</script>
<style lang="scss">
  .img-circle {
    border-radius: 50%;
    -webkit-border-radius: 50% !important;
    -moz-border-radius: 50% !important;
    -ms-border-radius: 50% !important;
    -o-border-radius: 50% !important;
    border-radius: 50% !important;
  }
</style>
